package cn.keniykey.mc.landterritory.landview;

import javax.annotation.Nullable;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import cn.keniykey.mc.landterritory.LandTerritoryMain;
import cn.keniykey.mc.landterritory.config.ConfigurationManager;
import cn.keniykey.mc.landterritory.config.LanguageManager;
import cn.keniykey.mc.landterritory.config.ViewsConfiguration;
import cn.keniykey.mc.landterritory.config.ViewsConfiguration.ViewConfig;
import cn.keniykey.mc.landterritory.event.LandUpdateDataEvent;
import cn.keniykey.mc.landterritory.land.LandManager;
import cn.keniykey.mc.landterritory.land.LandTransferUtil;
import cn.keniykey.mc.landterritory.land.RangeShowManager;
import cn.keniykey.mc.landterritory.land.api.Land;
import cn.keniykey.mc.landterritory.land.api.LandUtil;
import cn.keniykey.mc.landterritory.land.api.LandUtil.ELandPermissionLevel;
import cn.keniykey.mc.landterritory.toolkit.ArithmeticUtil;
import cn.keniykey.mc.landterritory.toolkit.Util;
import cn.keniykey.mc.landterritory.vault.Econ;
import cn.keniykey.mc.landterritory.vault.Perm;
import cn.keniykey.mc.viewlibrary.container.api.EContainerType;
import cn.keniykey.mc.viewlibrary.view.api.AbFrameView;
import cn.keniykey.mc.viewlibrary.view.api.FrameViewBundle;
import cn.keniykey.mc.viewlibrary.view.api.FrameViewIntent;
import cn.keniykey.mc.viewlibrary.view.api.IViewClickHandler;
import cn.keniykey.mc.viewlibrary.view.api.ViewClickReport;
import cn.keniykey.mc.viewlibrary.view.api.template.AbChooseView;
import cn.keniykey.mc.viewlibrary.view.api.template.AbChooseView.EChooseResultIntentKey;
import cn.keniykey.mc.viewlibrary.view.api.template.ChooseViewIntentBuilder;

public final class LandSoldInfoView extends AbLandFrameView{

	protected LandSoldInfoView(Player player1) {
		super(player1);
	}
	
	private static final String VIEW_NAME = "soldinfo";
	
	private static final int CODE_CHOOSE_BUY = 10600;
	private static final int CODE_CHOOSE_CANCEL = 10601;
	
	private Land land;
	
	@Override
	protected void onCreate() {
		super.onCreate();
		this.land = this.getIntent().getExtras().getValue("land", null);
		
		final ViewConfig config_view = ViewsConfiguration.getViewConfig(VIEW_NAME);
		this.setViewType(EContainerType.matchContainer(config_view.getViewSize()));
		this.setTitle(Util.conver(config_view.getViewTitle()));
		
		this.setIconClick(config_view.getViewItemSlot("back"), config_view.getViewItem("back"), AbLandFrameView.CLICK_BACK);
		this.setIconClick(config_view.getViewItemSlot("flags"), config_view.getViewItem("flags"), new IViewClickHandler() {
			@Override
			public void onClick(Player player, AbFrameView view, ViewClickReport report) {
				if(!LandSoldInfoView.this.isMatchClickSpeed()) return;
				final FrameViewIntent intent = new FrameViewIntent(LandFlagListView.class);
				final FrameViewBundle fvb = new FrameViewBundle();
				fvb.putValue("land", LandSoldInfoView.this.land);
				fvb.putValue("sold", true);
				intent.putExtras(fvb);
				view.showView(intent);
			}
		});
		this.setIconClick(config_view.getViewItemSlot("transfer"), config_view.getViewItem("transfer"), new IViewClickHandler() {	
			@Override
			public void onClick(Player player, AbFrameView view, ViewClickReport report) {
				if(!LandSoldInfoView.this.isMatchClickSpeed()) return;
				LandTransferUtil.transferLand(player, LandSoldInfoView.this.land, true, true);
				view.finishAll();
			}
		});
		this.setIconClick(config_view.getViewItemSlot("show"), config_view.getViewItem("show"), new IViewClickHandler() {
			@Override
			public void onClick(Player player, AbFrameView view, ViewClickReport report) {
				if(!LandSoldInfoView.this.isMatchClickSpeed()) return;
				RangeShowManager.showRange(player, LandSoldInfoView.this.land.getRange(), true);
				view.finishAll();
			}
		});
		this.setIconClick(config_view.getViewItemSlot("cancel"), config_view.getViewItem("cancel"), new IViewClickHandler() {
			@Override
			public void onClick(Player player, AbFrameView view, ViewClickReport report) {
				if(!LandSoldInfoView.this.isMatchClickSpeed()) return;
				final ChooseViewIntentBuilder builder = new ChooseViewIntentBuilder(LandChooseView.class);
				builder.setChooseCountdown(ConfigurationManager.View_Choose_Countdown);
				builder.setCustomPromptName(LanguageManager.getLang(1106100));
				builder.setCustomPromptLore(Util.listFromStr(LanguageManager.getLang(1106101,
						LandViewUtil.getLandLabelStr(LandSoldInfoView.this.land))));
				LandSoldInfoView.this.showViewForResult(builder.build(), CODE_CHOOSE_CANCEL);
			}
		});
		this.setIconClick(config_view.getViewItemSlot("buy"), new IViewClickHandler() {
			@Override
			public void onClick(Player player, AbFrameView view, ViewClickReport report) {
				if(!LandSoldInfoView.this.isMatchClickSpeed()) return;
				if(player.getUniqueId().equals(LandSoldInfoView.this.land.getOwner())) return;
				final ChooseViewIntentBuilder builder = new ChooseViewIntentBuilder(LandChooseView.class);
				builder.setChooseCountdown(ConfigurationManager.View_Choose_Countdown);
				builder.setCustomPromptName(LanguageManager.getLang(1106154));
				builder.setCustomPromptLore(Util.listFromStr(LanguageManager.getLang(1106155,
						LandViewUtil.getLandLabelStr(LandSoldInfoView.this.land),LandSoldInfoView.this.land.getPrice())));
				builder.setForwardContent(LandSoldInfoView.this.land.getPrice());
				LandSoldInfoView.this.showViewForResult(builder.build(), CODE_CHOOSE_BUY);
			}
		});
	}
	
	@Override
	protected void onShowBefore() {
		super.onShowBefore();
		final ViewConfig config_view = ViewsConfiguration.getViewConfig(VIEW_NAME);
		ItemStack item = config_view.getViewItem("about");
		ItemMeta meta = item.getItemMeta();
		meta.setDisplayName(Util.setStr(meta.getDisplayName(), this.land.getID(), this.land.getName()));
		meta.setLore(LandViewUtil.getLandInfoItemStack(this.land));
		item.setItemMeta(meta);
		this.setIcon(config_view.getViewItemSlot("about"), item);
		
		StringBuilder builder = new StringBuilder(LanguageManager.getLang(1106001));
		if(this.land.getPrice() > 0) {
			builder.append("\n").append(LanguageManager.getLang(1106000, this.land.getPrice()));
		}
		item = config_view.getViewItem("buy");
		meta = item.getItemMeta();
		meta.setLore(Util.listFromStr(builder.toString()));
		item.setItemMeta(meta);
		this.setIcon(config_view.getViewItemSlot("buy"), item);
	}
	
	@Override
	protected void onViewResult(int requestcode, int resultcode, @Nullable FrameViewBundle bundle) {
		super.onViewResult(requestcode, resultcode, bundle);
		switch(AbChooseView.EChooseResult.muchResult(resultcode)) {
		case CONFIRM:
			if(CODE_CHOOSE_BUY == requestcode) {
				buyLand(this.getPlayer(), this.land, bundle.getValue(EChooseResultIntentKey.FORWARD.toString(), 0));
				break;
			}
			if(CODE_CHOOSE_CANCEL == requestcode) {
				cancelLandSold(this.getPlayer(), this.land);
				break;
			}
			this.getPlayer().sendMessage(LanguageManager.getChatLang(1001001) + requestcode);
			break;
		case VETO: return;
		default:
		}
		this.finishAll();
	}
	
	static void cancelLandSold(final Player player,final Land land) {
		if(!LandUtil.hasLandPermission(player, land, ELandPermissionLevel.OWNER)) {
			player.sendMessage(LanguageManager.getChatLang(1005000, LandViewUtil.getLandLabelStr(land), 
					LanguageManager.getLang(1106102)));
			return;
		}
		if(!land.isDeleted() && land.getPrice() >= 0) {
			land.setPrice(-1);
			LandManager.getLandManager().getSoldLands().remove(LandManager.getLandManager().getSoldLands().indexOf(land));
			Bukkit.getPluginManager().callEvent(new LandUpdateDataEvent(player, land));
		}
		player.sendMessage(LanguageManager.getChatLang(1106103, LandViewUtil.getLandLabelStr(land)));
	}
	static void buyLand(final Player player,final Land land,final int price) {
		if(land.isDeleted()) return;
		final String buyper;
		switch(land.getType()) {
		case TERRITORY:
			buyper = ConfigurationManager.Territory_Sell_BuyPer;
			break;
		case COMMUNITY:
			buyper = ConfigurationManager.Community_Sell_BuyPer;
			break;
		case GROUND:
			buyper = ConfigurationManager.Ground_Sell_BuyPer;
			break;
		default:
			buyper = null;
		}
		if(buyper != null && !Perm.getPerm().hasPermission(land.getWorldName(), player, buyper)) {
			player.sendMessage(LanguageManager.getChatLang(1106150, LanguageManager.getLang(land.getType().getLang())));
			return;
		}
		if(land.getPrice() < 0 || land.getPrice() != price) {
			player.sendMessage(LanguageManager.getChatLang(1106151, LandViewUtil.getLandLabelStr(land)));
			return;
		}
		if(!LandUtil.canHasNewLand(player.getUniqueId(), land.getType())) {
			player.sendMessage(LanguageManager.getChatLang(1106152, LandViewUtil.getLandLabelStr(land)));
			return;
		}
		if(price > 0 && !player.isOp() && !Econ.getEcon().take(player, price)) {
			player.sendMessage(LanguageManager.getChatLang(1106153, LandViewUtil.getLandLabelStr(land), price));
			return;
		}
		double tax = 0d;
		switch(land.getType()) {
		case TERRITORY:
			if(!Perm.getPerm().hasPermission(land.getWorldName(), player, ConfigurationManager.Territory_Sell_NoTaxPer)) tax = ConfigurationManager.Territory_Sell_Tax;
			break;
		case COMMUNITY:
			if(!Perm.getPerm().hasPermission(land.getWorldName(), player, ConfigurationManager.Community_Sell_SellPer)) tax = ConfigurationManager.Community_Sell_Tax;
			break;
		case GROUND:
			if(!Perm.getPerm().hasPermission(land.getWorldName(), player, ConfigurationManager.Ground_Sell_NoTaxPer)) tax = ConfigurationManager.Ground_Sell_Tax;
			break;
		default:
		}
		final double pay = (tax > 0d ? ArithmeticUtil.subtract(price, ArithmeticUtil.multiply(price, tax, 2)) : price);
		if(pay > 0d && !Econ.getEcon().give(Bukkit.getOfflinePlayer(land.getOwner()), pay)) {
			if(!player.isOp() && !Econ.getEcon().give(player, price)) {
				LandTerritoryMain.getPlugin().getLogger().warning(LanguageManager.getLang(1001002, player.getName(),
						player.getUniqueId().toString(),price,"give"));
				player.sendMessage(LanguageManager.getChatLang(1001004, price));
				return;
			}
			player.sendMessage(LanguageManager.getChatLang(1001003));
			return;
		}
		LandManager.getLandManager().changeLandOwner(land, player.getUniqueId());
		Bukkit.getPluginManager().callEvent(new LandUpdateDataEvent(player, land));
		player.sendMessage(LanguageManager.getChatLang(1106158, price, LandViewUtil.getLandLabelStr(land)));
		final Player player_old_owner = Bukkit.getPlayer(land.getOwner());
		if(player_old_owner != null) player_old_owner.sendMessage(LanguageManager.getChatLang(1106159,
				LandViewUtil.getLandLabelStr(land), price, pay));
	}
}